<template>
  <div class="detail">
    <!-- 头部导航栏 -->
    <div class="header">
      <van-nav-bar
        style="background-color: #f4b4b6"
        title="个人信息"
        left-text="返回"
        fixed
        left-arrow
        @click-left="onClickLeft"
      />
      <!-- 占位 -->
      <div style="height: 60px"></div>
    </div>
    <div class="box">
      <!-- 头像 -->
      <van-cell style="margin-bottom: 10px">
        <template #title>
          <van-image
            round
            width="4rem"
            height="4rem"
            :src="userInfo.userFace"
          />
          <span class="name">用户名：{{ userInfo.username }}</span>
        </template>
        <template #right-icon>
          <van-button
            plain
            hairline
            type="info"
            size="small"
            @click="photoShow = true"
            >修改头像</van-button
          >
        </template>
      </van-cell>
      <!-- 信息 -->
      <div class="content">
        <van-cell
          title="姓名"
          is-link
          class="spanTitle"
          icon="user-o"
          :value="userForm.realname"
          @click="editInfo"
        ></van-cell>
        <van-cell
          title="性别"
          is-link
          class="spanTitle"
          icon="like-o"
          :value="gender"
          @click="editInfo"
        ></van-cell>
        <van-cell
          title="手机"
          is-link
          class="spanTitle"
          icon="phone-o"
          :value="userForm.telephone"
          @click="editInfo"
        ></van-cell>
        <van-cell
          title="邮箱"
          is-link
          class="spanTitle"
          icon="free-postage"
          :value="userForm.email"
          @click="editInfo"
        ></van-cell>
        <van-cell
          title="出生日期"
          is-link
          class="spanTitle"
          icon="birthday-cake-o"
          :value="userForm.birth | fmtDate_global"
          @click="editInfo"
        ></van-cell>
        <van-cell
          title="注册时间"
          is-link
          class="spanTitle"
          icon="clock-o"
          :value="userForm.registerTime | fmtDate_global"
        ></van-cell>
      </div>
      <!-- 密码 -->
      <van-cell
        title="修改密码"
        is-link
        class="spanTitle"
        icon="bag-o"
        @click="editPassword"
        style="margin-top: 20px"
      ></van-cell>

      <!-- 修改信息面板 -->
      <van-action-sheet v-model="show" title="修改信息">
        <div class="content">
          <van-field v-model="userForm.realname" label="姓名" placeholder="请输入姓名"/>
          <van-field name="userForm.gender" label="性别">
            <template #input>
              <van-radio-group v-model="userForm.gender" direction="horizontal">
                <van-radio name="male">男</van-radio>
                <van-radio name="female">女</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field v-model="userForm.telephone" label="手机" placeholder="请输入手机号"/>
          <van-field v-model="userForm.email" label="邮箱" placeholder="请输入邮箱"/>
          <van-field
            v-model="bgDate"
            label="出生日期"
            :placeholder="'请选择日期'"
            input-align="right"
            readonly
            right-icon="arrow"
            @click="showBeginDate"
          />
          <div style="margin: 16px">
            <van-button round block @click="submitInfo" class="subBtn"
              >提交</van-button
            >
          </div>
        </div>
      </van-action-sheet>

      <!--日期选择弹框-->
      <van-popup v-model="showPickerDate" position="bottom">
        <van-datetime-picker
          v-model="currentDate"
          type="date"
          @cancel="onCancelDate"
          @confirm="onConfirmDate"
          :min-date="minDate"
          :max-date="maxDate"
          :formatter="formatter"
        />
      </van-popup>

      <!-- 修改密码面板 -->
      <van-action-sheet v-model="passwordShow" title="修改密码">
        <div class="content">
          <van-field
            v-model="password"
            label="新密码"
            type="password"
            placeholder="密码长度大于3"
          />
          <van-field
            v-model="newPassword"
            label="确认密码"
            type="password"
            placeholder="请再次输入密码"
          />
          <div style="margin: 16px">
            <van-button round block @click="submitPassword" class="subBtn"
              >确定</van-button
            >
          </div>
        </div>
      </van-action-sheet>

      <!-- 修改头像面板 -->
      <van-action-sheet v-model="photoShow" title="修改头像">
        <div class="content">
          <van-field name="uploader" label="修改头像">
            <template #input>
              <van-uploader
                v-model="fileList"
                :after-read="afterRead"
                multiple
                :max-count="1"
              />
            </template>
          </van-field>
          <div style="margin: 16px">
            <van-button round block class="subBtn" @click="submitPhoto"
              >确定</van-button
            >
          </div>
        </div>
      </van-action-sheet>
      
    </div>
  </div>
</template>

<script>
import { get, post, post_formData } from "@/http/axios";
import { mapActions, mapState } from "vuex";
export default {
  data() {
    return {
      userForm: {},
      gender: "",
      show: false,
      passwordShow: false,
      photoShow: false,
      showDatePanel: false,
      // 新密码
      password: "",
      // 确认密码
      newPassword: "",
      // 上传的头像
      fileList: [],
      // 出生日期时间戳
      timestamp: "",
      minDate: new Date(1920, 0, 1),
      maxDate: new Date(),
      currentDate: new Date(),
      showPickerDate: false,
      bgDate: '', // 查询时间
    };
  },
  watch:{
    bgDate: function (val) {
      if (val === '') {
        return
      }
    }, 
  },
  computed: {
    // 引入用户信息对象
    ...mapState("user", ["userInfo"]),
  },
  methods: {
    // 引入用户数据
    ...mapActions("user", ["getUserInfo"]),
    // 将时间转换成时间戳
    changeTimeToChuo() {
      var date = new Date(this.bgDate);
      this.timestamp = date.getTime();
    },
    // 日期组件自定义格式
    formatter (type, value) {
      if (type === 'year') {
        this.value1 = value   // 可以拿到当前点击的数值
        return `${value}年`
      } else if (type === 'month') {
        this.value2 = value
        return `${value}月`
      }
      this.value3 = value
      return `${value}日`
    },
    onCancelDate () {
      this.showPickerDate = false
    },
    onConfirmDate () {
      this.bgDate = `${this.value1}-${this.value2}-${this.value3}`  // 字符串拼接 结果入2020-07-03
      this.changeTimeToChuo()
      this.onCancelDate()
    },
    // 显示查询日期
    showBeginDate () {
      this.showPickerDate = true
    },
    //文件上传后触发
    //detail 额外信息，包含 name 和 index 字段
    afterRead(file, detail) {
      console.log(this.dataURLtoFileFun(file.content));
      //定义⼀个formData表单对象
      let formData = new FormData();
      // 调⽤base64转⽂件对象⽅法进⾏格式转换
      formData.append("file", this.dataURLtoFileFun(file.content, "file.jpg"));
      // 使⽤post_formData⽅法将包含⽂件的formData上传到⽂件服务器⽂件服务器路径⻅swagger
      post_formData("http://121.199.29.84:8001/file/upload", formData).then(
        (res) => {
          if (res.data.status === 200) {
            //上传成功 将对应的图⽚路径保存到需要提交的表单对象中
            this.userForm.userFace=
              "http://121.199.29.84:8888/"+
              res.data.data.groupName+
              "/"+
              res.data.data.id;
              console.log(this.userForm.userFace,'-----------');
            // this.userForm.userFace=this.form.userFace
            // 保存已上传的⽂件路径
            this.fileList = [
              {
                url:
                  "http://121.199.29.84:8888/"+
                  res.data.data.groupName+
                  "/"+
                  res.data.data.id,
              },
            ];
          }
        }
      );
    },
    // bae64转⽂件对象
    dataURLtoFileFun(dataurl, filename) {
      // 将base64转换为⽂件，dataurl为base64字符串，filename为⽂件名（必须带后缀名，如.jpg,.png）
      let arr = dataurl.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    }, 
    // 提交头像修改
    submitPhoto() {
      let data={
        id:this.userForm.id,
        userface:this.userForm.userFace
      }
      post("/baseUser/alterUserface",data).then((res) => {
        if (res.data.status === 200) {
          this.$toast(res.data.message);
          // this.$router.push("mine");
          this.photoShow = false;
          // 刷新页面
          this.getUserInfo()
        } else {
          this.$toast(res.data.message);
        }
      });
    },
    // 提交密码
    submitPassword() {
      if (this.password.length > 3 && this.newPassword.length > 3) {
        this.$dialog
          .confirm({
            title: "修改密码",
            message: "你确定需要修改密码吗？",
          })
          .then(async () => {
            if (this.password == this.newPassword) {
              this.userForm.password = this.newPassword;
              let res = await post("/baseUser/saveOrUpdate", this.userForm);
              this.passwordShow = false;
              this.$toast.success(res.data.message);
            } else {
              this.passwordShow = false;
              this.$toast.fail("两次输入的密码不同");
            }
          })
          .catch(() => {});
      } else {
        this.$toast.fail("密码长度需大于3");
      }
    },
    // 提交用户信息
    async submitInfo() {
      this.userForm.birth=this.timestamp
      let res = await post("/baseUser/saveOrUpdate", this.userForm);
      this.showGender();
      // 刷新页面
      this.show = false;
    },

    // 格式化性别选项
    showGender() {
      if (this.userForm.gender == "female") {
        this.gender = "女";
      }
      if (this.userForm.gender == "male") {
        this.gender = "男";
      }
    },
    editInfo() {  
      this.show = true;
    },
    editPassword() {
      this.passwordShow = true;
      this.password = "";
      this.newPassword = "";
    },
    onClickLeft() {
      this.$router.go(-1);
    },

  },
  created() { 
    this.userForm = { ...this.userInfo };
    console.log(this.userForm);
    this.showGender(); 
  },
};
</script>
<style lang='less' scoped>
.subBtn {
  color: white;
  background-color: #f4b4b6;
}
.editPhoto {
  margin-left: 110px;
  margin-top: 25px;
}
.content .spanTitle {
  font-size: 15px;
  color: rgb(99, 99, 99);
}
.van-cell__value {
  flex: 2;
}
.van-cell__left-icon {
  margin-right: 8px;
  font-size: 20px;
  color: #f4b4b6;
}
.box .name {
  font-size: 16px;
  margin-left: 10px;
}
.detail {
  background-color: #f7f8fa;
  height: 650px;
}
/deep/ .van-nav-bar__title {
  color: #fff;
}
/deep/ .van-nav-bar__text {
  color: #fff;
}
/deep/ .van-icon-arrow-left {
  color: #fff;
}
</style>